package com.flyme.module.base.provider.controller;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.flyme.common.core.constants.CommonConstants;
import com.flyme.common.core.model.ResultBody;
import com.flyme.common.core.model.query.CriteriaQuery;
import com.flyme.common.core.model.query.PagerInfo;
import com.flyme.common.core.model.query.PqGrid;
import com.flyme.common.core.security.OpenHelper;
import com.flyme.common.core.security.OpenUserAuth;
import com.flyme.common.core.utils.ObjectUtils;
import com.flyme.core.base.supper.controller.BaseController;
import com.flyme.core.base.supper.entity.EntityMap;
import com.flyme.module.base.client.api.SysRegRemoteService;
import com.flyme.module.base.client.api.SysUserRemoteService;
import com.flyme.module.base.client.constants.BaseConstants;
import com.flyme.module.base.client.dto.SysUserDto;
import com.flyme.module.base.client.entity.SysUser;
import com.flyme.module.base.provider.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;

/**
 * 系统用户信息
 *
 * @author zyf
 */
@Api(tags = "系统用户管理")
@RestController
public class SysUserController extends BaseController<SysUserService, SysUser> implements SysUserRemoteService, SysRegRemoteService {

    @Autowired
    private SysAuthorizeService permissionService;
    @Autowired
    private SysAccountService sysAccountService;
    @Autowired
    private SysRoleService roleService;
    @Autowired
    private SysDeptService deptService;

    /**
     * 系统用户列表
     *
     * @return
     */
    @ApiOperation(value = "系统用户列表", notes = "系统用户列表")
    @PostMapping("/user/list")
    @Override
    public ResultBody list(@ModelAttribute PagerInfo pagerInfo, @ModelAttribute SysUser user) {
        CriteriaQuery cq = new CriteriaQuery<EntityMap>(pagerInfo);
        cq.select("u.id", "userName", "avatar", "mobile", "email", "age", "sex", "userType", "deptName", "positionName", "status", "u.createTime");
        cq.like("userName", user.getUserName());
        cq.in("userType", "UT_SYS", "UT_USER");
        cq.ne("userName", "admin");
        cq.eq("companyId", user.getCompanyId());
        PqGrid pqGrid = bizService.pageList(cq);
        return ResultBody.success(pqGrid);
    }

    /**
     * 选择用户
     *
     * @return
     */
    @ApiOperation(value = "选择用户", notes = "选择用户")
    @PostMapping("/user/chose")
    public ResultBody chose(@ModelAttribute PagerInfo pagerInfo, @ModelAttribute SysUser user) {
        OpenUserAuth userAuth = OpenHelper.getUserAuth();
        CriteriaQuery cq = new CriteriaQuery<EntityMap>(pagerInfo);
        cq.select("u.id", "userName", "avatar", "mobile", "email", "age", "sex", "userType", "deptName", "positionName", "status", "u.createTime");
        cq.like("userName", user.getUserName());
        cq.in("userType", user.getUserType());
        cq.ne("userName", "admin");
        cq.eq("companyId", userAuth.getCompanyId());
        PqGrid pqGrid = bizService.pageList(cq);
        return ResultBody.success(pqGrid);
    }

    @ApiOperation(value = "选择hr", notes = "选择hr")
    @PostMapping("/user/hrChose")
    public ResultBody hrChose(@ModelAttribute PagerInfo pagerInfo, @ModelAttribute SysUser user) {
        OpenUserAuth userAuth = OpenHelper.getUserAuth();
        CriteriaQuery cq = new CriteriaQuery<EntityMap>(pagerInfo);
        cq.select("u.id", "userName", "avatar", "mobile", "email", "age", "sex", "userType", "positionName", "status", "u.createTime");
        cq.like("userName", user.getUserName());
        cq.in("userType", user.getUserType());
        cq.ne("userName", "admin");
        cq.ne("u.id", userAuth.getUserId());
        cq.eq("companyId", userAuth.getCompanyId());
        PqGrid pqGrid = bizService.pageList(cq);
        List<EntityMap> list = (List<EntityMap>) pqGrid.getRows();
        for(EntityMap hr : list){
            String deptNames = deptService.getDeptName(hr.get("id"));
            hr.put("deptName", deptNames);
        }
        return ResultBody.success(pqGrid);
    }


    /**
     * 查询已选择系统用户
     *
     * @param user
     * @return
     */
    @ApiOperation(value = "添加系统用户", notes = "添加系统用户")
    @Override
    public ResultBody<List<Map<String, Object>>> getChosed(@RequestParam("userType") String userType, @RequestParam("userIds") String userIds) {
        List<Map<String, Object>> users = bizService.getSelectedUser(userType, userIds);
        return ResultBody.success().setData(users);
    }


    /**
     * 企业选择员工
     */
    @ApiOperation(value = "选择员工", notes = "选择员工")
    @PostMapping("/user/choseStaff")
    public ResultBody choseStaff(@ModelAttribute PagerInfo pagerInfo, @ModelAttribute SysUser user) {
        OpenUserAuth userAuth = OpenHelper.getUserAuth();//企业
        List<Long> deptIds = deptService.getDeptId(userAuth.getUserId());
        CriteriaQuery cq = new CriteriaQuery<EntityMap>(pagerInfo);
        cq.select("u.id", "userName", "avatar","nickName", "mobile", "email", "age", "sex", "userType", "dept.deptName", "positionName", "status", "u.createTime");
        cq.like("u.userName", user.getUserName());
        cq.in("u.userType", user.getUserType());
        cq.ne("u.userName", "admin");
        cq.in("u.deptId", deptIds);
        cq.eq("u.companyId", userAuth.getCompanyId());
        cq.createAlias("dept", "dept");
        PqGrid pqGrid = bizService.pageList(cq);
        return ResultBody.success(pqGrid);
    }

    /**
     * 添加系统用户
     *
     * @param user
     * @return
     */
    @ApiOperation(value = "添加系统用户", notes = "添加系统用户")
    @PostMapping("/user/add")
    @Override
    public ResultBody addUser(@ModelAttribute SysUserDto user) {
        Boolean tag = sysAccountService.register(user);
        return ResultBody.success("添加成功").setData(tag);
    }


    /**
     * 根据手机号注册用户
     *
     * @param mobile
     * @return
     */
    @Override
    public ResultBody regByMobile(@RequestParam("mobile") String mobile,String userType,Long invitedId) {
        SysUserDto user = new SysUserDto();
        user.setUserName("用户" + RandomUtil.randomString(8));
        user.setMobile(mobile);
        user.setPassword(CommonConstants.DEF_PWD);
        user.setAvatar("https://s1.ax1x.com/2018/05/19/CcdVQP.png");
        user.setUserType(userType);
        user.setReginvitedId(invitedId);
        user.setVipinvitedId(invitedId);
        user.setCourseinvitedId(invitedId);
        user.setExaminvitedId(invitedId);
        Boolean tag = sysAccountService.register(user);
        return ResultBody.success("添加成功").setData(tag);
    }

    /**
     * 更新系统用户
     *
     * @param user
     * @return
     */
    @ApiOperation(value = "更新系统用户", notes = "更新系统用户")
    @PostMapping("/user/edit")
    @Override
    public ResultBody updateUser(@ModelAttribute SysUser user) {
        Boolean tag = bizService.saveOrUpdate(user);
        if(tag) {
            UpdateWrapper u = new UpdateWrapper();
            sysAccountService.update(u.set(true, "account", user.getUserName()).eq(true, "userId", user.getId()));
        }
        if (ObjectUtils.isNotEmpty(user.getRoleIds())) {
            roleService.removeMemberRoles(user.getId());
        }
        roleService.saveUserRoles(user.getId(), user.getRoleIds());
        return ResultBody.success("更新成功").setData(tag);
    }

    /**
     * 删除用户
     */
    @ApiOperation(value = "删除用户", notes = "删除用户")
    @RequestMapping(value = "/user/delByIds/{userIds}", method = RequestMethod.DELETE)
    public ResultBody delByIds(@PathVariable Long[] userIds) {
        Boolean tag = bizService.delByIds(userIds);
        return ResultBody.success(tag);
    }

    /**
     * 解锁验证密码
     */
    @PostMapping(value = "/user/unlock")
    @ApiOperation(value = "解锁验证密码")
    @Override
    public ResultBody<Object> unLock(@RequestParam("password") String password) {
        if (!new BCryptPasswordEncoder().matches(password, OpenHelper.getUserAuth().getPassword())) {
            return ResultBody.failed("密码不正确");
        }
        return ResultBody.ok("解锁成功");
    }


    /**
     * 启用用户
     */
    @ApiOperation(value = "启用用户", notes = "启用用户")
    @PostMapping(value = "/user/enable/{id}")
    public ResultBody enable(@PathVariable("id") String id) {
        Boolean tag = bizService.updateStatus(id, BaseConstants.ENABLED);
        return ResultBody.success(tag);
    }

    /**
     * 禁用用户
     */
    @ApiOperation(value = "禁用用户", notes = "禁用用户")
    @PostMapping(value = "/user/disable/{id}")
    public ResultBody disable(@PathVariable("id") String id) {
        Boolean tag = bizService.updateStatus(id, BaseConstants.DISABLED);
        return ResultBody.success(tag);
    }

    @ApiOperation(value = "通过id查询用户")
    @Override
    public ResultBody get(@PathVariable() Long id) {
        SysUser user = bizService.getById(id);
        List<Long> roleIds = roleService.selectRoleIdsByUserId(id);
        user.setRoleIds(roleIds.toArray(new Long[roleIds.size()]));
        return ResultBody.success().setData(user);
    }


    /**
     * 当前用户可访问菜单资源
     *
     * @return
     */
    @ApiOperation(value = "当前用户可访问菜单资源", notes = "当前用户可访问菜单资源")
    @GetMapping("/user/grant/menus")
    public ResultBody userGrantMenus() {
        return ResultBody.success(permissionService.getUserGrantAccessList(OpenHelper.getUserAuth().getUserId(), BaseConstants.RESOURCE_TYPE_MENU));
    }

    /**
     * 当前用户可访问操作资源
     *
     * @return
     */
    @ApiOperation(value = "当前用户可访问操作资源", notes = "当前用户可访问操作资源")
    @GetMapping("/user/grant/actions")
    public ResultBody userGrantActions() {
        return ResultBody.success(permissionService.getUserGrantAccessList(OpenHelper.getUserAuth().getUserId(), BaseConstants.RESOURCE_TYPE_ACTION));
    }

    /**
     * 当前用户可访问接口资源
     *
     * @return
     */
    @ApiOperation(value = "当前用户可访问接口资源", notes = "当前用户可访问接口资源")
    @GetMapping("/user/grant/apis")
    public ResultBody userGrantApis() {
        return ResultBody.success(permissionService.getUserGrantAccessList(OpenHelper.getUserAuth().getUserId(), BaseConstants.RESOURCE_TYPE_API));
    }
}
